package command;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import Exceptions.ColumnNotFoundException;
import Exceptions.TableNotFoundException;
import XMLProcessing.DatabaseProcessing;
import XMLProcessing.TableProcessing;

public class SelectStatement implements ITreeNode, IStatement {
	private List<String> fields;
	private String table_name;
	private ConditionNode c;

	public SelectStatement(ArrayList<String> fields, String table_name,
			ConditionNode c) {
		this.fields = fields;
		this.table_name = table_name;
		this.c = c;
	}

	public SelectStatement(String table_name, ConditionNode c) {
		this.fields = null;
		this.table_name = table_name;
		this.c = c;
	}

	public SelectStatement(String table_name) {
		this.fields = null;
		this.table_name = table_name;
		this.c = null;
	}

	public SelectStatement(ArrayList<String> fields, String table_name) {
		this.fields = fields;
		this.table_name = table_name;
		this.c = null;
	}

	@Override
	public String toString() {
		String a;
		a = "Select statement \n";
		a += "Table :" + table_name + "\n";
		a += "Fields :";
		if (fields == null) {
			a += "*";
		} else {
			for (String t : fields) {
				a += t + ",";
			}
		}
		a += "\n";
		if (c != null) {
			a += "Conditions: " + this.c.toString();
		}
		return a;
	}

	@Override
	public ResultNode eval() throws ColumnNotFoundException,TableNotFoundException{
		String xmlFile = DatabaseProcessing.retrieveTable(table_name);
		ResultNode rN = null;
		
		if (fields !=null ){
			Map<Integer,List<String>> a = TableProcessing.retrieveValues(xmlFile,fields, c);
			rN = new ResultNode(a,fields,0);
		} else {
			fields = TableProcessing.getColumns(xmlFile);
			Map<Integer,List<String>> a = TableProcessing.retrieveValues(xmlFile,fields, c);
			rN = new ResultNode(a,fields,0);
		}
		
		return rN;
	}
}
